import axios from "axios";

const BASE_URL = "http://localhost:8080";

const oFile = document.querySelector("#file");
const oUploadBtn = document.querySelector("#uploadBtn");
const oUploadBase64Btn = document.querySelector("#uploadBase64Btn");
const oUploadBinaryBtn = document.querySelector("#uploadBinaryBtn");

oUploadBtn.addEventListener("click", () => {
  const file = oFile.files[0];
  const formData = new FormData();
  formData.append("file", file);

  axios
    .post(BASE_URL + "/file", formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    })
    .then((res) => {
      console.log(res);
    });
});
/**
 * base64上传
 */
oUploadBase64Btn.addEventListener("click", () => {
  const file = oFile.files[0];
  const reader = new FileReader();
  const ext = file.name.split(".")[1];
  reader.onload = (e) => {
    console.log(e.target.result);
    const uint8Array = new Uint8Array(e.target.result);
    const str = uint8Array.reduce((prev, byte) => {
      return prev + String.fromCharCode(byte);
    }, "");
    console.log("str", str);
    //字符串转换为base64
    const base64Data = btoa(str);
    axios
      .post(BASE_URL + "/base64", {
        ext,
        file: base64Data,
      })
      .then((res) => {
        console.log(res);
      });
  };
  reader.readAsArrayBuffer(file);
});

/**
 * 二进制上传
 */
oUploadBinaryBtn.addEventListener("click", () => {
  const file = oFile.files[0];
  const reader = new FileReader();

  reader.onloadend = () => {
    const binaryData = reader.result;

    axios
      .post(BASE_URL + "/binary", binaryData, {
        headers: {
          "Content-Type": "application/octet-stream",
          "x-ext": file.name.split(".")[1],
        },
      })
      .then((res) => {
        console.log(res);
      });
  };
  reader.readAsArrayBuffer(file);
});
